﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DNNspot.Licensing.Client;
using DNNspot.LiveChat.DataModel;
using DotNetNuke.Common;
using DotNetNuke.Entities.Host;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Entities.Modules.Actions;
using DotNetNuke.Entities.Users;
using DotNetNuke.Security;

namespace DNNspot.LiveChat
{
    public partial class Default : ModuleBase, IActionable
    {
        ModuleLicenseManager licenseManager;

        // ### EVENTS ######################################################

        protected void Page_PreRender(object sender, EventArgs e)
        {
            IncludeJS();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            HandlePostBack();

            if (!IsPostBack)
            {
                LoadControls();
            }

            licenseManager = new ModuleLicenseManager(LicenseSettings.LicenseKeySet, ModuleConfiguration.FolderName, this.ModuleConfiguration.ModuleName);
            //--- Check License
            bool isTrial = licenseManager.IsTrialLicense();
            if (isTrial)
            {
                if (IsEditable)
                {
                    string trialMsg = string.Format(@"This module is in TRIAL mode, you are limited to {0} messages per chat session.", LicenseSettings.TrialLicenseMaxMessagesPerSession - 3);
                    Controls.AddAt(0, new LiteralControl(licenseManager.GetLicenseStatusMessageHtml(trialMsg, true)));
                }
                Controls.Add(new LiteralControl(licenseManager.GetLicenseNagMessageHtml()));
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            PortalSetting.Set(PortalId, PortalSettingNames.WelcomeMessage, txtWelcomeMessage.Text);
            PortalSetting.Set(PortalId, PortalSettingNames.ChatOnlineMessage, txtChatOnlineMessage.Text);
            PortalSetting.Set(PortalId, PortalSettingNames.ChatOfflineMessage, txtChatOfflineMessage.Text);
            PortalSetting.Set(PortalId, PortalSettingNames.QueueTimeout, txtQueueTimeout.Text);
            PortalSetting.Set(PortalId, PortalSettingNames.QueueTimeoutMessage, txtQueueTimeoutMessage.Text);
        }

        // ### PRIVATE FUNCTIONS ###########################################

        private void HandlePostBack()
        {
            var target = Request.Form["__EVENTTARGET"];
            var argument = Request.Form["__EVENTARGUMENT"];

            if (target == PostBackEvents.EditAgent)
            {
                var agentId = Convert.ToInt32(argument);
                Response.Redirect(Globals.NavigateURL(TabId, ControlKeys.EditAgent, new[] {
                    string.Format("mid={0}", ModuleId),
                    string.Format("{0}={1}", Params.AgentId, agentId)
                }));
            }
            else if (target == PostBackEvents.EditCategory)
            {
                var categoryId = Convert.ToInt32(argument);
                Response.Redirect(Globals.NavigateURL(TabId, ControlKeys.EditCategory, new[] {
                    string.Format("mid={0}", ModuleId),
                    string.Format("{0}={1}", Params.CategoryId, categoryId)
                }));
            }
            else if (target == PostBackEvents.EditSession)
            {
                var sessionId = Convert.ToInt32(argument);
                Response.Redirect(Globals.NavigateURL(TabId, ControlKeys.EditSession, new[] {
                    string.Format("mid={0}", ModuleId),
                    string.Format("{0}={1}", Params.SessionId, sessionId)
                }));
            }
        }

        private void IncludeJS()
        {
            if (string.IsNullOrEmpty(HostSettings.GetHostSetting(ModuleSettings.NoJQuery)) && HttpContext.Current.Items["jquery_registered"] == null)
            {
                RegisterJavascript(String.Format("{0}{1}js/jquery-1.3.1.min.js", Globals.ApplicationPath, ModuleWebPath));
                HttpContext.Current.Items.Add("jquery_registered", "true");
            }

            RegisterJavascript(string.Format("{0}{1}js/dnnspot.livechat.admin.include.js", Globals.ApplicationPath, ModuleWebPath));
        }

        private void LoadControls()
        {
            txtWelcomeMessage.Text = PortalSetting.Get(PortalId, PortalSettingNames.WelcomeMessage) ?? "Waiting for agent to connect...";
            txtChatOnlineMessage.Text = PortalSetting.Get(PortalId, PortalSettingNames.ChatOnlineMessage) ?? "Live Chat";
            txtChatOfflineMessage.Text = PortalSetting.Get(PortalId, PortalSettingNames.ChatOfflineMessage) ?? "Live Chat Offline";
            txtQueueTimeout.Text = PortalSetting.Get(PortalId, PortalSettingNames.QueueTimeout) ?? "180";
            txtQueueTimeoutMessage.Text = PortalSetting.Get(PortalId, PortalSettingNames.QueueTimeoutMessage) ?? null;

            SetChatLink();
        }

        private void SetChatLink()
        {
            if (Agent.IsAgent(UserId))
                lnkChat.NavigateUrl = string.Format("{0}AgentChat.aspx", ModuleWebPath);
        }

        public DotNetNuke.Entities.Modules.Actions.ModuleActionCollection ModuleActions
        {
            get
            {
                ModuleActionCollection moduleActions = new ModuleActionCollection();

                moduleActions.Add(GetNextActionID(), "License", ModuleActionType.EditContent, "", "", EditUrl("License"), false, SecurityAccessLevel.Edit, true, false);

                return moduleActions;
            }
        }
    }
}

